package com.catmiao.spark.stream

import org.apache.spark.SparkConf
import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}
import org.apache.spark.streaming.{Seconds, StreamingContext}

/**
 * @title: SparkStreaming01_WordCount
 * @projectName spark_study
 * @description: TODO
 * @author ChengMiao
 * @date 2024/3/25 00:31
 */
object SparkStreaming08_Window {

  def main(args: Array[String]): Unit = {


    val sparkConf: SparkConf = new SparkConf().setMaster("local[*]").setAppName("SparkStreaming")
    val ssc = new StreamingContext(sparkConf, Seconds(3))

    val line: ReceiverInputDStream[String] = ssc.socketTextStream("localhost", 9999)

    val wordToOne: DStream[(String, Int)] = line.map((_, 1))

    // 窗口的范围应该是采集周期的整数倍
    // 窗口是可以滑动的 默认情况下一个采集周期进行滑动
    // 如果不想有重复数据计算，可以改变滑动幅度【步长】
    val windowDS: DStream[(String, Int)] = wordToOne.window(Seconds(6),Seconds(6))

    val value: DStream[(String, Int)] = windowDS.reduceByKey(_ + _)

    value.print()

    ssc.start()
    ssc.awaitTermination()
  }


}
